var strophe = require('../../utils/strophe.js')
var WebIM = require('../../utils/WebIM.js')
var WebIM = WebIM.default
var app = getApp();
var yourname1;
var msg;
var isinto = false;
var falg = null;
var kaiguan = false;
 
var RecordStatus = {
  SHOW: 0,
  HIDE: 1,
  HOLD: 2,
  SWIPE: 3,
  RELEASE: 4
}

var RecordDesc = {
  0: '长按开始录音',
  2: '向上滑动取消',
  3: '松开手取消',
}


Page({
  data: {
    emojiStr: '',
    yourname: '',
    myName: '',
    sendInfo: '',
    userMessage: '',
    inputMessage: '',
    indicatorDots: true,
    autoplay: false,
    interval: 5000,
    duration: 1000,
    show: 'emoji_list',
    view: 'scroll_view',
    toView: '',
    emoji: WebIM.Emoji,
    emojiObj: WebIM.EmojiObj,
    msgView: {},
    RecordStatus: RecordStatus,
    RecordDesc: RecordDesc,
    recordStatus: RecordStatus.HIDE,
    userPhoto:'',
    showView:false,
    isShow:false,
    msgArr:[],
    isinto:false,
    chatMsg:[]
  },
  getRoomPage: function () {
    return this.getPage("pages/chat/chat")
  },
  getPage: function (pageName) {
    var pages = getCurrentPages()
    return pages.find(function (page) {
      return page.__route__ == pageName
    })
  },
  onUnload:function(){
     
  },

  onShow: function () {
    var that = this;
     var your = wx.getStorageSync('your')
    var myName = wx.getStorageSync('myUsername')
    var personArr = wx.getStorageSync('personArr') || []
    var uid = wx.getStorageSync('uid')
     var name = wx.getStorageSync('name')
   var pic = wx.getStorageSync('pic')
   var applogin = wx.getStorageSync('applogin')
  //console.log(applogin)
   //var applogin = 1

     that.setData({
       isShow: true,
       applogin:applogin
     })



   console.log('personArr',personArr)
    var arr = []
    var person = {}
    for (var key in personArr) {
      if (personArr[key].id == your && !personArr[key].id2) {
        for(var j=personArr[key].MsgArr.length-1;j>=0;j--){

          if (!personArr[key].MsgArr[j].isin){
            for (var n in personArr[key].MsgArr[j].data){
              var itm = personArr[key].MsgArr[j].data[n]
             
                if (itm.type == 'txt') {
                  var value = WebIM.parseEmoji(itm.data.replace(/\n/mg, ''))
                  var type1 = itm.type
                } else if (itm.type == 'emoji') {
                  var value = personArr[key].MsgArr[j].data
                  var type1 = itm.type
                }
                if (itm.type == 'emoji') {
                  var value = personArr[key].MsgArr[j].data
                  var type1 = itm.type
                } else if (itm.type == 'txt') {
                  var value = personArr[key].MsgArr[j].data
                  var type1 = itm.type
                }
                if (personArr[key].MsgArr[j].type == 'img') {
                  var value = personArr[key].MsgArr[j].data
                  var type1 = personArr[key].MsgArr[j].type
                }
             
             
             
            } 
           
           
            console.log(value)
       
            var time = WebIM.time()
            var msgData = {
              info: {
                from: personArr[key].id,
                to: uid
              },
              //
              username: personArr[key].name,
              yourname: personArr[key].id,
              headerUrl: personArr[key].pic,
              nickName: personArr[key].name,
              msg: {
                type: type1,
                data: value,
                url: personArr[key].pic
              },
              type: type1,
              style: '',
              time: time,
              //mid: chatMsg2[key].type + chatMsg2[key].id
            }
            if (personArr[key].id == your) {
              msgData.style = 'selg'
              //msgData.username = chatMsg2[key].info.from
            } else {
              msgData.style = 'self'
              //msgData.username = chatMsg2[key].info.to
            }

            personArr[key].MsgArr[j].isin = true

            var chatMsg = that.data.chatMsg
            chatMsg.push(msgData)
            console.log(chatMsg)
            wx.setStorage({
              key: your + myName,
              data: that.data.chatMsg,
              success: function () {
                console.log('success', that.data)
                that.setData({
                  chatMsg: that.data.chatMsg,
                })
                setTimeout(function () {
                  that.setData({
                    //toView: that.data.chatMsg[that.data.chatMsg.length - 1].mid
                  })
                }, 100)
              }
            })
           
          }

          
        }
       
         try {
          wx.setStorageSync('personArr', personArr)

        } catch (e) {
        }
      }
    }


       //信息提示
        // var kaiguan = false
        // kaiguan = wx.getStorageSync('kaiguan') || null;
        // for(var k=0;k<personArr.length;k++){
        //   if (personArr[k].id == your && personArr[k].MsgArr&&!kaiguan){
        //     that.setData({
        //       showView: true
        //     })
        //     // kaiguan = true
        //     // break;
        //   }
        
        // }
      

  },

  opaBox: function () {
    var that = this;
    that.setData({
      isShow: false
    })
  },

  onLoad: function (options) {
    var that = this
    var myName = wx.getStorageSync('myUsername')
    
    var personArr = wx.getStorageSync('personArr') || [];
     var myName = wx.getStorageSync('myUsername')
    var uid = wx.getStorageSync('uid');
   // var personArr = wx.getStorageSync('personArr') || [];
    var your = wx.getStorageSync('your');
    console.log('personArr',personArr)

    //console.log(chatMsg1)

   


    //console.log(myName)
    // var option = {}
    // option.apiUrl = options.apiUrl
    // option.user = options.user
    // option.pwd = options.pwd
    // option.appKey = options.appKey



    var options = JSON.parse(options.username)
    console.log(options)
    
    var your = options.your
    var pick = options.userAvatar
    var name = options.yourName
 
    try {
      wx.setStorageSync('your', your)
      wx.setStorageSync('pick', pick)
      wx.setStorageSync('name', name)
    } catch (e) {
    }


    //var your = options.username
    var num = wx.getStorageSync(options.your + myName).length - 1
    if (num > 0) {
      setTimeout(function () {
        that.setData({
          toView: wx.getStorageSync(options.your + myName)[num].mid
        })
      }, 10)
    }
    // WebIM.conn.open(option)

    that.setData({
      yourname: options.your,
      yourname1: options.yourName,
      myName: myName,
      inputMessage: '',
      chatMsg: wx.getStorageSync(options.your + myName) || []

    })


    wx.setNavigationBarTitle({
      title: that.data.yourname1
    })

  

  },


  //接收消息封装函数
  receiveImage: function (msg, type) {
    var that = this
    // var msg = wx.getStorageSync('message')
    // console.log(msg)
    var myName = wx.getStorageSync('myUsername')
    if (msg) {
      console.log(msg)
      var time = WebIM.time()
      var msgData = {
        info: {
          from: msg.from,
          to: msg.to
        },
        username: msg.from,
        yourname: msg.from,
        headerUrl: msg.ext.headerUrl,
        nickName: msg.ext.nickName,
        msg: {
          type: 'img',
          data: msg.url
        },
        style: '',
        time: time,
        mid: 'img' + msg.id
      }
      //console.log(msgData)
      that.data.chatMsg.push(msgData)
      console.log(that.data.chatMsg)
      wx.setStorage({
        key: that.data.yourname + myName,
        data: that.data.chatMsg,
        success: function () {
          //console.log('success', that.data)
          that.setData({
            chatMsg: that.data.chatMsg
          })
          setTimeout(function () {
            that.setData({
              toView: that.data.chatMsg[that.data.chatMsg.length - 1].mid
            })
          }, 100)
        }
      })

      var personArr = wx.getStorageSync('personArr') || []
      //var pic = wx.getStorageSync('pic');
      var obj = {}
      obj.id = msg.from
      obj.name = msg.ext.nickName
      obj.pic = msg.ext.headerUrl
      var MsgArr = obj.MsgArr || []

      var o = {}
      o.time = time
      o.data = msg.url
      o.type = 'img'
      MsgArr.unshift(o)
      console.log(MsgArr)
      obj.MsgArr = MsgArr

      var isext = false;
      for (var i = 0; i < personArr.length; i++) {
        if (personArr[i].id == obj.id) {
          personArr[i].MsgArr[0] = obj.MsgArr[0]
          isext = true;
          break;
        }

      }
      if (!isext) {
        personArr.unshift(obj)
      }
      console.log('personArr', personArr)
      try {
        wx.setStorageSync('personArr', personArr)
      } catch (e) {
      }
    }
  },
 
  receiveMsg: function (msg, type) {
    var that = this
    var myName = wx.getStorageSync('myUsername')
    
    if (msg.from == that.data.yourname || msg.to == that.data.yourname) {
      if (type == 'txt') {
        var value = WebIM.parseEmoji(msg.data.replace(/\n/mg, ''))
      } else if (type == 'emoji') {
        var value = msg.data
      }
      console.log('msg', msg)
      console.log(value)

      var time = WebIM.time()
      var msgData = {
        info: {
          from: msg.from,
          to: msg.to
        },
        //
        username: msg.from,
        yourname: msg.from,
        headerUrl: msg.ext.headerUrl,
        nickName: msg.ext.nickName,
        msg: {
          type: type,
          data: value,
          url: msg.url
        },
        style: '',
        time: time,
        mid: msg.type + msg.id
      }
      if (msg.from == that.data.yourname) {
        msgData.style = 'selg'
        msgData.username = msg.from
      } else {
        msgData.style = 'self'
        msgData.username = msg.to
      }
      //console.log(msgData, that.data.chatMsg, that.data)
      that.data.chatMsg.push(msgData)
      wx.setStorage({
        key: that.data.yourname + myName,
        data: that.data.chatMsg,
        success: function () {
          console.log('success', that.data)
          that.setData({
            chatMsg: that.data.chatMsg,
          })
          setTimeout(function () {
            that.setData({
              toView: that.data.chatMsg[that.data.chatMsg.length - 1].mid
            })
          }, 100)
        }
      })

      var personArr = wx.getStorageSync('personArr')||[]
      //var pic = wx.getStorageSync('pic');
      var obj = {}
      obj.id = msg.from
      obj.name = msg.ext.nickName
      obj.pic = msg.ext.headerUrl
      var MsgArr = obj.MsgArr || []

      var o = {}
      o.time = time
      o.data = value
      MsgArr.unshift(o)
      console.log(MsgArr)
      obj.MsgArr = MsgArr

      var isext = false;
      for (var i = 0; i < personArr.length; i++) {
        if (personArr[i].id == obj.id) {
          personArr[i].MsgArr[0] = obj.MsgArr[0]
          
          isext = true;
          break;
        }

      }
      if (!isext) {
        personArr.unshift(obj)
      }
      console.log('personArr', personArr)
      try {
        wx.setStorageSync('personArr', personArr)
      } catch (e) {
      }
    }
  },
  

  

  // close:function(){
  //     this.setData({
  //       showView:false
  //     })
  //     kaiguan = true
  //     try {
  //       wx.setStorageSync('kaiguan', kaiguan);
  //     } catch (e) {
  //     }

  // },

  bindMessage: function (e) {
    this.setData({
      userMessage: e.detail.value
    })
  },
  cleanInput: function () {
    var that = this
    var setUserMessage = {
      sendInfo: that.data.userMessage
    }
    that.setData(setUserMessage)
  },
  //***************** 录音 begin ***************************
  changedTouches: null,
  toggleRecordModal: function (e) {
    this.setData({
      recordStatus: this.data.recordStatus == RecordStatus.HIDE ? RecordStatus.SHOW : RecordStatus.HIDE
    })
  },
  toggleWithoutAction: function (e) {
    console.log('toggleWithoutModal 拦截请求不做处理')
  },
  handleRecordingMove: function (e) {
    var touches = e.touches[0]
    var changedTouches = this.changedTouches

    if (!this.changedTouches) {
      return
    }
    // 无效
    // var changedTouches = e.changedTouches[0]
    // console.log(changedTouches.pageY, touches.pageY)

    if (this.data.recordStatus == RecordStatus.SWIPE) {
      if (changedTouches.pageY - touches.pageY < 20) {
        this.setData({
          recordStatus: RecordStatus.HOLD
        })
      }
    }
    if (this.data.recordStatus == RecordStatus.HOLD) {
      if (changedTouches.pageY - touches.pageY > 20) {
        this.setData({
          recordStatus: RecordStatus.SWIPE
        })
      }
    }

  },
  handleRecording: function (e) {
    var self = this
    console.log('handleRecording')
    this.changedTouches = e.touches[0]
    this.setData({
      recordStatus: RecordStatus.HOLD
    })
    wx.startRecord({
      fail: function (err) {
        // 时间太短会失败
        console.log(err)
      },
      success: function (res) {
        console.log('success')
        // 取消录音发放状态 -> 退出不发送
        if (self.data.recordStatus == RecordStatus.RELEASE) {
          console.log('user canceled')
          return
        }
        // console.log(tempFilePath)
        self.uploadRecord(res.tempFilePath)
      },
      complete: function () {
        console.log("complete")
        this.handleRecordingCancel()
      }.bind(this)
    })

    setTimeout(function () {
      //超时 
      self.handleRecordingCancel()
    }, 100000)
  },
  handleRecordingCancel: function () {
    console.log('handleRecordingCancel')
    // 向上滑动状态停止：取消录音发放
    if (this.data.recordStatus == RecordStatus.SWIPE) {
      this.setData({
        recordStatus: RecordStatus.RELEASE
      })
    } else {
      this.setData({
        recordStatus: RecordStatus.HIDE
      })
    }
    wx.stopRecord()
  },
  stopRecord: function (e) {
    let {url, mid} = e.target.dataset
    this.data.msgView[mid] = this.data.msgView[mid] || {}
    this.data.msgView[mid].isPlay = false;
    this.setData({
      msgView: this.data.msgView
    })
    wx.stopVoice()
  },
  playRecord: function (e) {
    let {url, mid} = e.target.dataset
    this.data.msgView[mid] = this.data.msgView[mid] || {}

    // reset all plays
    for (let v in this.data.msgView) {
      this.data.msgView[v] = this.data.msgView && (this.data.msgView[v] || {})
      this.data.msgView[v].isPlay = false
    }

    // is play then stop
    if (this.data.msgView[mid].isPlay) {
      this.stopRecord(e)
      return;
    }

    console.log(url, mid)
    this.data.msgView[mid].isPlay = true;
    this.setData({
      msgView: this.data.msgView
    })

    wx.downloadFile({
      url: url,
      success: function (res) {
        wx.playVoice({
          filePath: res.tempFilePath,
          complete: function () {
            this.stopRecord(e)
          }.bind(this)
        })
      }.bind(this),
      fail: function (err) {
      },
      complete: function complete() {
      }
    })
  },
  uploadRecord: function (tempFilePath) {
    var str = WebIM.config.appkey.split('#')
    var that = this
    wx.uploadFile({
      url: 'https://a1.easemob.com/' + str[0] + '/' + str[1] + '/chatfiles',
      filePath: tempFilePath,
      name: 'file',
      header: {
        'Content-Type': 'multipart/form-data'
      },
      success: function (res) {
        // return;

        // 发送xmpp消息
        var msg = new WebIM.message('audio', WebIM.conn.getUniqueId())
        var data = res.data
        var dataObj = JSON.parse(data)
        var myName = wx.getStorageSync('myUsername')
        var thumb = wx.getStorageSync('thumb')
        var file = {
          type: 'audio',
          'url': dataObj.uri + '/' + dataObj.entities[0].uuid,
          'filetype': '',
          'filename': tempFilePath
        }
        var option = {
          apiUrl: WebIM.config.apiURL,
          body: file,
          to: that.data.yourname,                  // 接收消息对象
          roomType: false,
          chatType: 'singleChat',
           ext: { 'nickName': myName, 'headerUrl': thumb },
        }
        msg.set(option)
        WebIM.conn.send(msg.body)
        // 本地消息展示
        var time = WebIM.time()
        var msgData = {
          info: {
            to: msg.body.to
          },
          myname: that.data.myName,
          yourname: msg.body.to,
          userPhoto: thumb,
          msg: {
            type: msg.type,
            data: msg.body.body.url,
            url: msg.body.body.url,
          },
          style: 'self',
          time: time,
          mid: msg.id
        }
        that.data.chatMsg.push(msgData)
        console.log(that.data.chatMsg)
        // 存储到本地消息
        var myName = wx.getStorageSync('myUsername')
        wx.setStorage({
          key: that.data.yourname + myName,
          data: that.data.chatMsg,
          success: function () {
            //console.log('success', that.data)
            that.setData({
              chatMsg: that.data.chatMsg
            })
            setTimeout(function () {

              that.setData({
                toView: that.data.chatMsg[that.data.chatMsg.length - 1].mid
              })
            }, 10)
          }
        })
      }
    })
  },
  //***************** 录音 end ***************************


  // 发送消息
  
  sendMessage: function () {

    if (!this.data.userMessage.trim()) return;


    var that = this
    // console.log(that.data.userMessage)
    // console.log(that.data.sendInfo)
    var myName = wx.getStorageSync('myUsername')
    var thumb = wx.getStorageSync('thumb')
    var uid = wx.getStorageSync('uid')
    var id = WebIM.conn.getUniqueId();
    var msg = new WebIM.message('txt', id);

    var personArr = wx.getStorageSync('personArr') || []


    msg.set({
      msg: that.data.sendInfo,
      to: that.data.yourname,
      action: 'action',
      ext: { 'nickName': myName, 'headerUrl': thumb},
      
      roomType: false,
      success: function (id, serverMsgId) {
        console.log('success')
      },
      fail: function (res) {
        console.log('fail',res);
      }
    });
    console.log(msg)
    msg.body.chatType = 'singleChat';
    // msg.body.nickName = myName;
    // msg.body.yourname = yourname1;
    // msg.body.headerUrl = thumb;
    
    WebIM.conn.send(msg.body);
    if (msg) {
      var value = WebIM.parseEmoji(msg.value.replace(/\n/mg, ''))
      
      var time = WebIM.time()
      var msgData = {
        info: {
          to: msg.body.to
        },
        myname: that.data.myName,
        yourname: msg.body.to,
        userPhoto: thumb,
        username: that.data.yourname1,
        msg: {
          type: msg.type,
          data: value
        },
        style: 'self',
        time: time,
        mid: msg.id
      }
      that.data.chatMsg.push(msgData)
       console.log(that.data.chatMsg)

       var pic = wx.getStorageSync('pick');
       
       var obj = {}
       obj.id = msg.body.to
       obj.id2 = uid
       obj.name = that.data.yourname1
       obj.pic = pic
       var MsgArr = obj.MsgArr || []

       var o = {}
       o.time = time
       o.data = value
       MsgArr.unshift(o)
       console.log(MsgArr)
      
       obj.MsgArr = MsgArr

       var isext = false;
       for (var i = 0; i < personArr.length; i++) {
         if (personArr[i].id == obj.id) {
          
          personArr[i].MsgArr[0] = obj.MsgArr[0]
         
           personArr[i].id2 = obj.id2
           isext = true;
           break;
         }

       }
       if (!isext) {
         personArr.unshift(obj)
       }
       console.log('personArr', personArr)
       try {
         wx.setStorageSync('personArr', personArr)
       } catch (e) {
       }
      
       

       //聊天记录缓存
      wx.setStorage({
        key: that.data.yourname + myName,
        data: that.data.chatMsg,
        success: function () {
          //console.log('success', that.data)
          that.setData({
            chatMsg: that.data.chatMsg,
            emojiList: [],
            inputMessage: ''
          })
          setTimeout(function () {
            that.setData({
              toView: that.data.chatMsg[that.data.chatMsg.length - 1].mid
            })
          }, 100)
        }
        
      })
      //提示消息
      // kaiguan = wx.getStorageSync('kaiguan') || null;
      // var chatMsg = that.data.chatMsg
      // var len = chatMsg.length
      // console.log(len)
      // if (len == 1&&!kaiguan) {
      //   that.setData({
      //     showView: true
      //   })
      // } else {
      //   that.setData({
      //     showView: false
      //   })
      // }
      that.setData({
        userMessage: ''
      })
    }
    
  },

  openEmoji: function () {
    this.setData({
      show: 'showEmoji',
      view: 'scroll_view_change'
    })
  },
  sendEmoji: function (event) {
    var that = this
    var emoji = event.target.dataset.emoji
    var msglen = that.data.userMessage.length - 1
    if (emoji && emoji != '[del]') {
      var str = that.data.userMessage + emoji
    } else if (emoji == '[del]') {
      var start = that.data.userMessage.lastIndexOf('[')
      var end = that.data.userMessage.lastIndexOf(']')
      var len = end - start
      if (end != -1 && end == msglen && len >= 3 && len <= 4) {
        var str = that.data.userMessage.slice(0, start)
      } else {
        var str = that.data.userMessage.slice(0, msglen)
      }
    }
    this.setData({
      userMessage: str,
      inputMessage: str
    })
  },
  sendImage: function () {
    var that = this
    var pages = getCurrentPages()
    console.log(pages)
    //pages[1].cancelEmoji() || pages[2].cancelEmoji()
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album'],
      success: function (res) {
        //console.log(res)
        //console.log(pages)
        if (pages[1].route == 'pages/chat/chat') {
          pages[1].upLoadImage(res, that)
         
        } 
        if (pages[2].route == 'pages/chat/chat') {
          pages[2].upLoadImage(res, that)
         
        }
        if (pages[3].route == 'pages/chat/chat'){
          pages[3].upLoadImage(res, that) 
        }
       
      }
    })
  },
  


  // sendVideo: function() {
  //     var that = this
  //     wx.chooseVideo({
  //         sourceType: ['album', 'camera'],
  //         maxDuration: 60,
  //         camera: 'back',
  //         success: function(res) {
  //             console.log(res)
  //             var tempFilePaths = res.tempFilePath
  //             var str = WebIM.config.appkey.split('#')
  //             wx.uploadFile({
  //                 url: 'https://a1.easemob.com/'+ str[0] + '/' + str[1] + '/chatfiles',
  //                 filePath: tempFilePaths,
  //                 name: 'file',
  //                 header: {
  //                     'Content-Type': 'multipart/form-data'
  //                 },
  //                 success: function (res) {
  //                         var data = res.data

  //                         var dataObj = JSON.parse(data)
  //                         console.log(dataObj)
  //                         var id = WebIM.conn.getUniqueId();                   // 生成本地消息id
  //                         var msg = new WebIM.message('img', id);
  //                         console.log(msg)
  //                         var file = {
  //                             type: 'img',
  //                             'url': dataObj.uri + '/' + dataObj.entities[0].uuid,
  //                             'filetype': 'mp4',
  //                             'filename': tempFilePaths
  //                         }
  //                         //console.log(file)
  //                         var option = {
  //                             apiUrl: WebIM.config.apiURL,
  //                             body: file,
  //                             to: that.data.yourname,                  // 接收消息对象
  //                             roomType: false,
  //                             chatType: 'singleChat'
  //                         }
  //                         msg.set(option)
  //                         WebIM.conn.send(msg.body)
  //                         if (msg) {
  //                             //console.log(msg,msg.body.body.url)
  //                             var time = WebIM.time()
  //                             var msgData = {
  //                                 info: {
  //                                     to: msg.body.to
  //                                 },
  //                                 username: that.data.myName,
  //                                 yourname: msg.body.to,
  //                                 msg: {
  //                                     type: msg.type,
  //                                     data: msg.body.body.url
  //                                 },
  //                                 style: 'self',
  //                                 time: time,
  //                                 mid: msg.id
  //                             }
  //                             that.data.chatMsg.push(msgData)
  //                             console.log(that.data.chatMsg)
  //                             var myName = wx.getStorageSync('myUsername')
  //                             wx.setStorage({
  //                                 key: that.data.yourname + myName,
  //                                 data: that.data.chatMsg,
  //                                 success: function () {
  //                                     //console.log('success', that.data)
  //                                     that.setData({
  //                                         chatMsg: that.data.chatMsg
  //                                     })
  //                                     setTimeout(function () {
  //                                         that.setData({
  //                                             toView: that.data.chatMsg[that.data.chatMsg.length - 1].mid
  //                                         })
  //                                     }, 10)
  //                                 }
  //                             })
  //                         }

  //                 }
  //             })
  //         }
  //     })
  // },
 

  openCamera: function () {
    var that = this
    var pages = getCurrentPages()
    //pages[1].cancelEmoji() || pages[2].cancelEmoji()
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['camera'],
      success: function (res) {
        if (pages[1].route == 'pages/index/index' && pages[2].route == 'pages/chat/chat') {
          pages[2].upLoadImage(res, that)
        } else if (pages[1].route == 'pages/chat/chat') {
          pages[1].upLoadImage(res, that)
        }
      }
    })
  },
  focus: function () {
    this.setData({
      show: 'emoji_list',
      view: 'scroll_view'
    })
  },
  cancelEmoji: function () {
    this.setData({
      show: 'emoji_list',
      view: 'scroll_view'
    })
  },
  scroll: function (e) {
    // //console.log(e)
  },
  lower: function (e) {
    //console.log(e)
  },
  upLoadImage: function (res, that) {
    //console.log(res)
    var tempFilePaths = res.tempFilePaths
    //console.log(tempFilePaths)
    wx.getImageInfo({
      src: res.tempFilePaths[0],
      success: function (res) {
         console.log(res)
        var allowType = {
          'jpg': true,
          'gif': true,
          'png': true,
          'bmp': true
        };
        var str = WebIM.config.appkey.split('#')
        var width = res.width
        var height = res.height
        var index = res.path.lastIndexOf('.')
        if (index != -1) {
          var filetype = res.path.slice(index + 1)
        }
        if (filetype.toLowerCase() in allowType) {
          wx.uploadFile({
            url: 'https://a1.easemob.com/' + str[0] + '/' + str[1] + '/chatfiles',
            filePath: tempFilePaths[0],
            name: 'file',
            header: {
              'Content-Type': 'multipart/form-data'
            },
            success: function (res) {
              var data = res.data
              var dataObj = JSON.parse(data)
              // console.log(dataObj)
              var id = WebIM.conn.getUniqueId();                   // 生成本地消息id
              var msg = new WebIM.message('img', id);
              var myName = wx.getStorageSync('myUsername')
              var thumb = wx.getStorageSync('thumb')
              var uid = wx.getStorageSync('uid')
              var pic = wx.getStorageSync('pick')
              var personArr = wx.getStorageSync('personArr') || []
              var file = {
                type: 'img',
                size: {
                  width: width,
                  height: height
                },
                'url': dataObj.uri + '/' + dataObj.entities[0].uuid,
                'filetype': filetype,
                'filename': tempFilePaths[0]
              }
              //console.log(file)
              var option = {
                apiUrl: WebIM.config.apiURL,
                body: file,
                to: that.data.yourname,                  // 接收消息对象
                roomType: false,
                chatType: 'singleChat',
                ext: { 'nickName': myName, 'headerUrl': thumb },
              }
              msg.set(option)
              WebIM.conn.send(msg.body)
              if (msg) {
                //console.log(msg,msg.body.body.url)
                var time = WebIM.time()
                var msgData = {
                  info: {
                    to: msg.body.to
                  },
                  myname: that.data.myName,
                  yourname: msg.body.to,
                  userPhoto: thumb,
                  msg: {
                    type: msg.type,
                    data: msg.body.body.url,
                    size: {
                      width: msg.body.body.size.width,
                      height: msg.body.body.size.height,
                    }
                  },
                  style: 'self',
                  time: time,
                  mid: msg.id
                }
                that.data.chatMsg.push(msgData)
                //console.log(that.data.chatMsg)

                var obj = {}
                obj.id = msg.body.to
                obj.id2 = uid
                obj.name = that.data.yourname1
                obj.pic = pic
                var MsgArr = obj.MsgArr || []

                var o = {}
                o.time = time
                o.data = '[图片]'
                o.type = 'img'
                MsgArr.unshift(o)
                console.log(MsgArr)
                obj.MsgArr = MsgArr

                var isext = false;
                for (var i = 0; i < personArr.length; i++) {
                  if (personArr[i].id == obj.id) {
                    personArr[i].MsgArr[0] = obj.MsgArr[0]
                    personArr[i].id2 = obj.id2
                    isext = true;
                    break;
                  }

                }
                if (!isext) {
                  personArr.unshift(obj)
                }
                console.log('personArr', personArr)
                try {
                  wx.setStorageSync('personArr', personArr)
                } catch (e) {
                }

                wx.setStorage({
                  key: that.data.yourname + myName,
                  data: that.data.chatMsg,
                  success: function () {
                    console.log('success', that.data)
                    that.setData({
                      chatMsg: that.data.chatMsg
                    })
                    setTimeout(function () {
                      that.setData({
                        toView: that.data.chatMsg[that.data.chatMsg.length - 1].mid
                      })
                    }, 10)
                  }
                })
              }
            }
          })
        }
      }
    })
  },

  previewImage: function (event) {
    var url = event.target.dataset.url
    wx.previewImage({
      urls: [url]  // 需要预览的图片http链接列表
    })
  },
  globalData: {
    userInfo: null,
    chatMsg: []
  }
})

















